package postgres

import (
	"manager/model"
	"manager/model/entity"
)

var EbikeType = &ebikeType{}

type ebikeType struct{}

func (a *ebikeType) Create(m *entity.EbikeType) (int64, error) {
	err := db.Create(m).Error
	return m.ID, err
}

func (a *ebikeType) Find(id int64) (*entity.EbikeType, error) {
	e := &entity.EbikeType{}
	err := db.Model(&entity.EbikeType{}).First(&e, id).Error
	return e, err
}

func (a *ebikeType) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.EbikeType{}).Where("id = ?", id).Updates(dict).Error
}

func (a *ebikeType) Delete(id int64) error {
	return db.Delete(&entity.EbikeType{}, id).Error
}

func (a *ebikeType) List(in *model.EbikeTypeListRequest) (int, []*model.EbikeTypeListInfoResponse, error) {
	type CountType struct {
		Count  int64 `json:"count"`
		TypeID int64 `json:"type_id"`
	}
	var (
		q               = db.Model(&entity.EbikeType{})
		err             error
		total           int64
		ebikeTypes      = make([]*entity.EbikeType, 0)
		ebikeTypeChilds = make([]*entity.EbikeType, 0)
		out             = make([]*model.EbikeTypeListInfoResponse, 0)
		countTypes      = make([]*CountType, 0)
		parentIds       []int64
	)

	if in.Name != nil && *in.Name != "" {
		q = q.Where("name like ?", "%"+*in.Name+"%")
	}
	if in.SocketType != nil {
		q = q.Where("socket_type = ?", *in.SocketType)
	}
	if in.Price != nil {
		q = q.Where("price = ?", *in.Price)
	}

	if in.ID != nil {
		q = q.Where("parent_id = ?", *in.ID)
	} else {
		q = q.Where("parent_id = ?", 0)
	}
	if in.Status != nil {
		q = q.Where("status = ?", *in.Status)
	}

	if in.Code != nil {
		q = q.Where("code = ?", *in.Code)
	}

	if err = q.Count(&total).Error; err != nil {
		return 0, out, err
	}
	// 查询所有父级

	if err = q.Order("created_at desc").Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&ebikeTypes).Error; err != nil {
		return 0, out, err
	}

	if len(ebikeTypes) == 0 { //没查询到结果直接返回
		return 0, out, err
	}
	parentIds = make([]int64, len(ebikeTypes))
	for i, response := range ebikeTypes {
		out = append(out, &model.EbikeTypeListInfoResponse{
			ID:         response.ID,
			Name:       response.Name,
			CreatedAt:  response.CreatedAt,
			UpdatedAt:  response.UpdatedAt,
			SocketType: response.SocketType,
			Status:     response.Status,
			Price:      response.Price,
			Color:      response.Color,
			HasChild:   false,
		})
		parentIds[i] = response.ID
	}
	// 统计数据每个型号下面的车辆数量
	err = db.Model(&entity.Ebike{}).Select("count(id)", "type_id").Where("type_id in (?)", parentIds).Group("type_id").Find(&countTypes).Error
	if err != nil {
		return 0, nil, err
	}
	for _, et := range out {
		for _, countType := range countTypes {
			if et.ID == countType.TypeID {
				et.Count = countType.Count
			}
		}
	}
	// 通过父ID 查询所有子
	err = db.Model(&entity.EbikeType{}).Where("parent_id in (?)", parentIds).Find(&ebikeTypeChilds).Error
	if err != nil {
		return 0, nil, err
	}

	for i, parent := range out {
		for _, child := range ebikeTypeChilds {
			if parent.ID == child.ParentID {
				out[i].HasChild = true
			}
		}
	}

	return int(total), out, nil
}

func (a *ebikeType) ParentList(in *model.ParentEbikeTypeRequest) ([]*model.ParentEbikeTypeList, error) {
	var (
		err error
		q   = db.Model(&entity.EbikeType{})
		out = make([]*model.ParentEbikeTypeList, 0)
	)

	if in.ID > 0 {
		q = q.Where("id =  ?", in.ID)
	}

	if len(in.IDs) > 0 {
		q = q.Where("id IN ?", in.IDs)
	}

	if in.Name != "" {
		q = q.Where("name like ?", "%"+in.Name+"%")
	}
	if in.QueryAll != nil {
		if *in.QueryAll == 0 {
			q = q.Where("parent_id = 0")
		}
	}

	err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&out).Error
	return out, err
}

func (a *ebikeType) EbikeList(in *model.ParentEbikeTypeRequest) ([]*model.ParentEbikeTypeList, error) {
	var (
		err error
		q   = db.Model(&entity.EbikeType{})
		out = make([]*model.ParentEbikeTypeList, 0)
	)

	if in.Name != "" {
		q = q.Where("name like ?", "%"+in.Name+"%")
	}

	err = q.Where("parent_id = 0").Find(&out).Error
	return out, err
}
